<?php

namespace App\Http\Controllers;

use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Requests\BookingRequest;
use App\Booked;
use App\Handlers\ImageUploadHandler;
use Qcloud\Sms\SmsSingleSender;
use App\User;

class BookingController extends Controller
{
    private $appid = '1400387932',$appkey = '918c930f489431dbea5b1b28fc5b2cd7',$tempId,$single;

    public function create(Request $request){

       /* if (!$request->maintain) {
            return '<h4>维护中……请10点之后再来预约，对你们造成的不便我们深表歉意</h4>';
        }*/

        $app = getOfficialAccount();

        $config = $app->jssdk->buildConfig(array(	'getLocalImgData',
                'checkJsApi',
                'previewImage',
                'uploadImage',
                'chooseImage',
                'getLocalImg'), false,false,true);


        $user_id = session('user')->id;

        return view('booking.create',compact('config','user_id'));
    }

    public function successReply(Request $request)
    {
        $id = $request->input('id');
        $this->single = Booked::find($id);
        $result = [];

        $this->single->content = $this->single->booking_date.' '.$this->single->time_range;
        $this->tempId = '642501';
        $result = $this->send(1);

        echo json_encode($result);
    }

    public function failReply(Request $request)
    {
        $id = $request->input('id');
        $this->single = Booked::find($id);
        $result = [];

        $this->single->content = $request->input('content');
        $this->tempId = '642499';
        $result = $this->send(2);

        echo json_encode($result);
    }

    protected function send($reply)
    {
        // 指定模板ID单发短信
        try {
            $sender = new SmsSingleSender($this->appid, $this->appkey);
            $params = [$this->single->plate_number.' ',$this->single->content];
            $result = $sender->sendWithParam("86", $this->single->phone, $this->tempId,
                $params,  "晋诚仓储", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
            $result = json_decode($result,1);
            if($result['errmsg'] === 'OK'){
                $result['msg'] = '短信发送成功';
            }else{
                $result['msg'] = '短信发送异常';
            }
            $result['msg'] = $this->tempSend($result['msg'],$reply);
            unset($this->single->content);
            $this->single->is_reply = $reply;
            $this->single->save();
        } catch(\Exception $e) {
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    public function tempSend($msg,$reply){
        $user = User::find($this->single->user_id);
        $data = [
            'first' => '晋诚仓储预约通知',
            'keyword1' => $this->single->name,
            'keyword2' => $this->single->phone,
            'keyword3' => $this->single->created_at,
        ];
        if($reply === 1){
            $data['keyword4'] = '制卡成功';

            $data['remark'] = '您好，'.$this->single->plate_number.' 制卡已经成功，预约时间为 '.$this->single->booking_date.' '.$this->single->time_range.'，请携带身份证刷卡入闸。如有疑问请致电：020-84968826';
        }else if($reply === 2){
            $data['keyword4'] = '制卡失败';

            $data['remark'] = '您好，'.$this->single->plate_number.' 制卡失败，'.$this->single->content.' 请重新提交预约。如有疑问请致电：020-84968826';
        }
        $config = [
            'app_id' => config('app.WECHAT_APP_ID'),
            'secret' => config('app.WECHAT_APP_SECRET'),
            'token' => config('app.WECHAT_APP_TOKEN'),
            'response_type' => 'array'
        ];
        $app = Factory::officialAccount($config);

        $result = $app->template_message->send([
            'touser' => $user->openid,
            'template_id' => config('app.WECHAT_APP_TEMPID'),
            'data' => $data,
        ]);

        if($result['errcode'] === 43004){
            $msg .= '，用户未关注公众号不能推送消息';
        }else if($result['errcode'] === 0){
            $msg .= '，公众号模板消息推送成功';
        }else{
            $msg .= '，公众号模板消息推送异常：'.$result['errmsg'];
        }

        return $msg;
    }


    public function store(BookingRequest $request,ImageUploadHandler $uploader,Booked $booked)
    {
        $data = $request->all();
        $result = Booked::where('plate_number',$data['plate_number'])
                ->where('booking_date',$data['booking_date'])
                ->where('time_range',$data['time_range'])
                ->first();
        if($result){
            return redirect()->route('Booking.create')->with('danger', '提交失败！请不要在同一时间段重复提交');
        }

        //图片上传处理
        $files = '';
        $counter = 0;
        $data['files'] = explode('mark-booking',$data['files']);
        foreach ($data['files'] as $file){
            $result = $uploader->wechatImageSaveToOss($file, 'booked',$data['user_id']);
            if($result){
                if($counter){
                    $files .= ','.$result['path'];
                }else{
                    $files .= $result['path'];
                }
            }
            $counter++;
        }
        $data['files'] = $files;
        $booked = $booked->create($data);

        $this->sendWarning($booked,User::find($booked->user_id));

        return redirect()->route('Booking.create')->with('success', '提交成功! 请等待我们的短信通知');
    }

    /*
     * 下单发送提醒
     * */
    public function sendWarning(Booked $booked,User $user){
        $data = [
            'first' => '晋诚仓储预约通知',
            'keyword1' => $booked->name,
            'keyword2' => $booked->phone,
            'keyword3' => $booked->created_at,
            'keyword4' => '预约受理中，请等待受理回复',
            'remark' => '抵达仓库后，下车务必佩戴安全帽及反光衣。码头内限速30KM/S，安检部门会不定期检查如被抓拍将会罚款100元。（仓库有临时安全帽提供，但出于个人卫生问题，建议自备。）'
        ];

        $config = [
            'app_id' => config('app.WECHAT_APP_ID'),
            'secret' => config('app.WECHAT_APP_SECRET'),
            'token' => config('app.WECHAT_APP_TOKEN'),
            'response_type' => 'array'
        ];
        $app = Factory::officialAccount($config);

        $app->template_message->send([
            'touser' => $user->openid,
            'template_id' => config('app.WECHAT_APP_TEMPID'),
            'data' => $data,
        ]);

        /*$result = $app->template_message->send([
            'touser' => $user->openid,
            'template_id' => config('app.WECHAT_APP_TEMPID'),
            'data' => $data,
        ]);

        if($result['errcode'] === 43004){
            $msg .= '，用户未关注公众号不能推送消息';
        }else if($result['errcode'] === 0){
            $msg .= '，公众号模板消息推送成功';
        }else{
            $msg .= '，公众号模板消息推送异常：'.$result['errmsg'];
        }

        return $msg;*/
    }
}
